package com.atguigu.exam.service.impl;

import com.atguigu.exam.entity.AnswerRecord;
import com.atguigu.exam.entity.ExamRecord;
import com.atguigu.exam.entity.Paper;
import com.atguigu.exam.entity.Question;
import com.atguigu.exam.exception.ExamException;
import com.atguigu.exam.mapper.AnswerRecordMapper;
import com.atguigu.exam.mapper.ExamRecordMapper;
import com.atguigu.exam.service.AIService;
import com.atguigu.exam.service.AnswerRecordService;
import com.atguigu.exam.service.ExamRecordService;
import com.atguigu.exam.service.PaperService;
import com.atguigu.exam.vo.ExamRankingVO;
import com.atguigu.exam.vo.GradingResult;
import com.atguigu.exam.vo.StartExamVo;
import com.atguigu.exam.vo.SubmitAnswerVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 考试记录Service实现类
 * 实现考试记录相关的业务逻辑
 */
@Service
public class ExamRecordServiceImpl extends ServiceImpl<ExamRecordMapper, ExamRecord> implements ExamRecordService {

    @Autowired
    private PaperService paperService;
    @Autowired
    private AnswerRecordService answerRecordService;
    @Autowired
    private AnswerRecordMapper answerRecordMapper;
    @Autowired
    private AIService aiService;


    @Override
    public ExamRecord startExam(StartExamVo startExamVo) {
        LambdaQueryWrapper<ExamRecord> startExamVoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        startExamVoLambdaQueryWrapper.eq(ExamRecord::getExamId,startExamVo.getPaperId())
                .eq(ExamRecord::getStudentName,startExamVo.getStudentName())
                .eq(ExamRecord::getStatus,"进行中");
        ExamRecord examRecord = baseMapper.selectOne(startExamVoLambdaQueryWrapper);
        if (examRecord==null){
            ExamRecord record = new ExamRecord();
            record.setStudentName(startExamVo.getStudentName());
            record.setExamId(startExamVo.getPaperId());
            record .setStatus("进行中");
            record.setStartTime(LocalDateTime.now());
            baseMapper.insert(record);
        }
        return examRecord;
    }

    @Override
    public ExamRecord getExamDetailById(Integer id) {
        ExamRecord examRecord = baseMapper.selectById(id);
        Paper paperDetailById = paperService.getPaperDetailsById(examRecord.getExamId());
        examRecord.setPaper(paperDetailById);
        List<AnswerRecord> answerRecordList = answerRecordMapper.selectList(new LambdaQueryWrapper<AnswerRecord>().eq(AnswerRecord::getExamRecordId, id));
        examRecord.setAnswerRecords(answerRecordList);
        return examRecord;
    }

    @Override
    public void submitAnswers(Integer examRecordId, List<SubmitAnswerVo> answers) {
//        设置结束时间
        ExamRecord examRecord = baseMapper.selectById(examRecordId);
        examRecord.setEndTime(LocalDateTime.now());
        examRecord.setStatus("已完成");
//        刷新
        baseMapper.updateById(examRecord);

        List<AnswerRecord> answerRecordList = answers.stream().map(answer -> new AnswerRecord(examRecordId, answer.getQuestionId(), answer.getUserAnswer())).collect(Collectors.toList());

        answerRecordService.saveBatch(answerRecordList);

        gradePaper(examRecordId);
    }


    //  判卷
    private void gradePaper(Integer examRecordId) {
//        根据答题记录id拿到答题记录
        ExamRecord examRecordDetailById = getExamDetailById(examRecordId);
//       根据答题记录获取试卷再拿到题目详情
        List<Question> questionList = examRecordDetailById.getPaper().getQuestions();
        Map<Long, Question> questionMap = questionList.stream().collect(Collectors.toMap(Question::getId, question -> question));

        List<AnswerRecord> answerRecords = examRecordDetailById.getAnswerRecords();
//      统计答对题的数量
        AtomicInteger atomicInteger = new AtomicInteger();

        answerRecords.forEach(answerRecord -> {
            Long questionId = answerRecord.getQuestionId();
            Question question = questionMap.get(questionId);

            String userAnswer = answerRecord.getUserAnswer();

            if (!"TEXT".equals(question.getType())){
                if ("JUDGE".equals(question.getType())){
                    userAnswer = userAnswer.equals("T")?"TRUE":"FALSE";
                }
                if (userAnswer.equals(question.getAnswer().getAnswer())){
                    answerRecord.setScore(question.getPaperScore().intValue());
                    answerRecord.setIsCorrect(1);
                    atomicInteger.set(atomicInteger.get() + 1);
                }else {
                    answerRecord.setScore(0);
                    answerRecord.setIsCorrect(0);
                }
            }else {
                GradingResult gradingResult = aiService.gradeTextQuestions(question, userAnswer);
                Integer score = gradingResult.getScore();
                answerRecord.setScore(score);
                if(score.equals(0)){
                    //该简答题没有得分
                    answerRecord.setIsCorrect(0);
                    //设置ai批改意见
                    answerRecord.setAiCorrection(gradingResult.getReason());
                }else if(score.equals(question.getPaperScore().intValue())){
                    //该简单题得了满分
                    answerRecord.setIsCorrect(1);
                    //设置ai批改意见
                    answerRecord.setAiCorrection(gradingResult.getFeedback());
                    //对答对数量加1
                    atomicInteger.set(atomicInteger.get() + 1);
                }else{
                    answerRecord.setIsCorrect(2);
                    answerRecord.setAiCorrection(gradingResult.getReason());
                    atomicInteger.set(atomicInteger.get() + 1);
                }
            }
            answerRecordMapper.updateById(answerRecord);
        });
        //获取当前试卷所有题目的总分
        int totalPaperScore = questionList.stream().mapToInt(question -> question.getPaperScore().intValue()).sum();
        //计算用户的总得分
        int totalScore = answerRecords.stream().filter(answerRecord -> answerRecord.getIsCorrect() != 0).mapToInt(AnswerRecord::getScore).sum();
        //设置当前试卷的总分数
        examRecordDetailById.setScore(totalScore);
        //调用AI给出当前考试的评语
        //设置考试记录的状态
        examRecordDetailById.setStatus("已批阅");
        //调用AI获取考试评语
        String answer = aiService.getExamAnswer(totalScore,totalPaperScore,questionList.size(),atomicInteger);
        //设置AI评语
        examRecordDetailById.setAnswers(answer);
        //更新考试记录
        baseMapper.updateById(examRecordDetailById);
    }


    @Override
    public void deleteExamRecordById(Integer id) {
        boolean exists = baseMapper.exists(new LambdaQueryWrapper<ExamRecord>().eq(ExamRecord::getStatus, "进行中").eq(ExamRecord::getId,id));
        if(exists){
            throw new ExamException(1007,"进行中状态的考试记录不能删除");
        }
        baseMapper.deleteById(id);
        answerRecordMapper.delete(new LambdaQueryWrapper<AnswerRecord>().eq(AnswerRecord::getExamRecordId,id));
    }

    @Override
    public List<ExamRankingVO> getExamRanking(Integer paperId, Integer limit) {
        return baseMapper.getExamRanking(paperId,limit);
    }

}